import {
    createRouter,
    createWebHashHistory,
    createWebHistory,
    RouteRecordRaw
} from 'vue-router'
import {App} from "vue";
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import {Session} from "@/utils/storage";
import useRouterList from "@/store/module/routerList";
import pinia from "@/store";
import {MenuEnum} from "@/store/enum/MenuEnum";
import {common} from "@/constance/common";

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
        meta: {
            title: '登陆页面'
        }
    },
    {
        path: '/',
        name: 'BasicLayout',
        redirect: '/home',
        component: () => import('@/layout/index.vue'),
        children: [
            {
                path: '/home',
                name: 'Home',
                component: () => import('@/views/home/index.vue'),
                meta: {
                    title: '首页'
                }
            }
        ],
    },
    {
        path: '/:catchAll(.*)',
        name: 'NoPage404',
        component: () => import('@/views/404/index.vue'),
        meta: {
            title: '404'
        }
    },
]

const router = createRouter({
    history: createWebHistory(),
    // routes: [] //路由配置
    routes  //key value一样可以简写
})

// 关闭 loading 图标
nprogress.configure({showSpinner: false})
router.beforeEach(async (to,
                         from,
                         next) => {
    let title: string = to.meta.title as string
    window.document.title = title ? title : 'Vite + Vue3 + Ts'
    // 开始加载进度条
    if (to.name) nprogress.start()
    const token = Session.get('token');
    if (to.path === '/login' && !token) {
        next();
        nprogress.done();
    } else {
        if (!token) {
            next(`/login`);
            Session.clear();
            nprogress.done();
        } else if (token && to.path === '/login') {
            next('/');
            nprogress.done();
        } else {
            let useRouterListStore = useRouterList(pinia);
            if (useRouterListStore.menuList.length) {
                // 路由组件名称（自定义）
                const title: any = to.meta?.title;
                const path: any = to.path;
                // 当前路由匹配到name
                const name: any = to.name;
                useRouterListStore.setActiveView(path)
                useRouterListStore.setCacheView(name)
                useRouterListStore.setToolData({name, path, title})
                next();
            } else {
                // 增加以下代码，判断是否存在临时路由，存在则删除
                if (router.hasRoute('temp')) {
                    router.removeRoute('temp')
                }
                useRouterListStore.setMenu()
                //如果 addRoute 并未完成，路由守卫会一层一层的执行执行，直到 addRoute 完成，找到对应的路由
                next({path: to.path, replace: true})
            }
        }
    }
})

router.afterEach(() => {
    // 结束加载进度条
    nprogress.done()
})


export const initRouter = (app: App<Element>) => {
    app.use(router)
}

/**
 * 动态生成路由
 * @param data
 * @param parent
 */
export const dynamicRouter = (data: IMenuItem[], parent: any) => {
    // @ts-ignore
    const modulesViews = import.meta.glob("../views/**/**.vue")
    //const modulesLayout = import.meta.glob("../layout/components/mainView/index.vue")
    // let superName: string
    // if (!parent) {
    //     superName = common.basicLayout
    // } else {
    //     superName = parent.name
    // }
    data.filter(item => {
        // if (item.type == MenuEnum.CATALOG) {
        //     router.addRoute(superName, {
        //         path: `${item.path}`,
        //         name: item.name,
        //         //需要用vite规定的导入方式导入,否则打包后部署到服务器报错找不到动态导入的文件
        //         //对应上方的const modules = import.meta.glob("../views/**/**.vue")
        //         component: modulesLayout[`../layout/components/mainView/index.vue`],
        //         meta: {
        //             title: item.title,
        //             icon: item.icon
        //         }
        //     })
        // } else
        // 菜单
        if (item.type == MenuEnum.ROUTE) {
            if (parent && !parent?.redirect) {
                parent!.redirect = `${item.path}`
            }
            router.addRoute(common.basicLayout, {
                path: `${item.path}`,
                name: item.name,
                //需要用vite规定的导入方式导入,否则打包后部署到服务器报错找不到动态导入的文件
                //对应上方的const modules = import.meta.glob("../views/**/**.vue")
                component: modulesViews[`../views/${item.component}.vue`],
                meta: {
                    title: item.title,
                    icon: item.icon,
                    parent: parent
                }
            })
        }
        // 目录
        if (item.type == MenuEnum.CATALOG) {
            // 是否存在子集
            if (item.children && item.children.length) {
                dynamicRouter(item.children, {
                    path: `${item.path}`,
                    name: item.name,
                    meta: {
                        title: item.title,
                        icon: item.icon,
                        parent: parent
                    }
                });
            }
        }
    });
};
// @ts-ignore
if (!router.hasRoute()) {
    router.addRoute({
        path: window.location.pathname,
        name: 'temp',
        component: () => import('@/layout/components/mainView/index.vue')
    })
}

// 一个文件默认导出只能有一个
export default router
